package com.example.demo2.service.impl;

import com.example.demo2.entity.Result;
import com.example.demo2.mapper.ResultMapper;
import com.example.demo2.service.ResultService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

/**
 * ResultServiceImpl 实现类，用于根据公式获取结果的分页数据
 * @version 1.0
 * @date 2024/6/20 15:38
 */
@Service
public class ResultServiceImpl implements ResultService {

    @Autowired
    private ResultMapper resultMapper;

    @Override
    public Page<Result> getResultsByFormula(String formula, int page, int size) {
        int validatedPage = page > 0 ? page : 1;
        int offset = (validatedPage - 1) * size;
        List<Result> results = resultMapper.findByFormula(formula, offset, size);
        int total = resultMapper.countByFormula(formula);

        // 保留四位小数
        results.forEach(result -> result.setResult(
                BigDecimal.valueOf(result.getResult()).setScale(4, RoundingMode.HALF_UP).doubleValue()
        ));

        return new PageImpl<>(results, PageRequest.of(validatedPage - 1, size), total);
    }

    @Override
    public Page<Result> getResultsByFormulaAndName(String formula, String name, int page, int size) {
        int offset = page * size;
        List<Result> results = resultMapper.findByFormulaAndName(formula, name, offset, size);
        int total = resultMapper.countByFormulaAndName(formula, name);

        // 保留四位小数
        results.forEach(result -> result.setResult(
                BigDecimal.valueOf(result.getResult()).setScale(4, RoundingMode.HALF_UP).doubleValue()
        ));

        return new PageImpl<>(results, PageRequest.of(page, size), total);
    }
    @Override
    public List<Result> getResultsByName(String name) {
        return resultMapper.findByName(name);
    }
    @Cacheable("resultNames")
    @Override
    public List<String> getAllResultNames() {
        return resultMapper.findAllDistinctNames();
    }
}
